package com.xugongzhang.service;

import com.xugongzhang.dto.Message;
import com.xugongzhang.enums.MessageTypeEnum;
import com.xugongzhang.thread.ManageClientConnectServerThread;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * @author X
 * @date 2022/11/27 16:45
 */
public class MessageClientService {

    /**
     * 私聊
     * @param info 消息内容
     * @param sender 发送消息的人
     * @param getter 接收消息的人
     */
    public void sendMessageToOne(String info, String sender, String getter) {
        Message message = new Message();
        message.setMsgType(MessageTypeEnum.COMM_MSG.getMessageType());
        message.setSender(sender);
        message.setGetter(getter);
        message.setContent(info);
        message.setSendTime(new Date().toString());
        System.out.println(sender + " 对 " + getter + " 说：" + info);
        // 发送消息
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread
                    .getClientConnectServerThread(sender).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void sendMsgToAll(String info, String sender) {
        Message message = new Message();
        message.setMsgType(MessageTypeEnum.TO_ALL_MSG.getMessageType());
        message.setContent(info);
        message.setSender(sender);
        message.setSendTime(new Date().toString());
        System.out.println(sender + " 对大家说：" + info);
        // 发送消息
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread
                    .getClientConnectServerThread(sender).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
